package com.pro01.carcontrol.encode;

public class CarEncode {

    public static String trackingOpenEncode() {
        return baseEncode("63");
    }

    public static String trackingCloseEncode() {
        return baseEncode("64");
    }

    public static String takePhotosEncode() {
        return baseEncode("60");
    }

    public static String startRecordingEncode() {
        return baseEncode("61");
    }

    public static String closeRecordingEncode() {
        return baseEncode("62");
    }

    public static String ctrlCarEncode(int speedX, int speedY) {
        speedX = formatSpeed(speedX);
        speedY = formatSpeed(speedY);
        return baseEncode("10",
                numberToHex(speedX, 2) + numberToHex(speedY, 2));
    }

    public static String buttonCarEncode(CarDirection d) {
        return baseEncode("15", numberToHex(d.getCode(), 2));
    }

    public static String upSpeedCarEncode(int l1, int l2, int r1, int r2) {
        l1 = formatSpeed(l1);
        l2 = formatSpeed(l2);
        r1 = formatSpeed(r1);
        r2 = formatSpeed(r2);

        return baseEncode("21",
                numberToHex(l1, 2),
                numberToHex(l2, 2),
                numberToHex(r1, 2),
                numberToHex(r2, 2));
    }

//    public static String baseEncode(String type, String... datas) {
//        StringBuilder info = new StringBuilder();
//        for (String s : datas) info.append(s);
//        int size = (info.length() / 2) + 2;
//        String sizeHex = numberToHex(size, 2);
//
//        String code = "01" + type + sizeHex + info;
//        String checksum = numberToHex(getChecksum(code), 2);
//        return "$" + code + checksum + "#";
//    }
public static String baseEncode(String type, String... datas) {
    StringBuilder info = new StringBuilder();
    for (String s : datas) info.append(s);

    // —— 关键修正：长度按 “十六进制字符个数” 计算 ——
    int size = info.length() + 2;                    // payload 字符数 + checksum 两字符
    String sizeHex = numberToHex(size, 2);

    String code = "01" + type + sizeHex + info;
    String checksum = numberToHex(getChecksum(code), 2);
    return "$" + code + checksum + "#";
}

    private static int formatSpeed(int value) {
        value = Math.round(value);
        if (value < 0) value += 256;
        return value;
    }

    public static String numberToHex(int num, int len) {
        String hex = Integer.toHexString(num).toUpperCase();
        while (hex.length() < len) hex = "0" + hex;
        return hex;
    }

    public static int getChecksum(String data) {
        int checksum = 0;
        for (int i = 0; i < data.length(); i += 2) {
            String byteStr = data.substring(i, Math.min(i + 2, data.length()));
            try {
                int value = Integer.parseInt(byteStr, 16);
                checksum = (checksum + value) % 256;
            } catch (Exception ignored) {
            }
        }
        return checksum;
    }
}